app.controller('TrainningCategoryCtrl', [
    '$scope', 'alertService', 'trainningService', '$modal',
    function ($scope, alertService, trainningService, $modal) {
        trainningService.getAsync(false, 'TrainningCategory')
            .then(function (result) {
                $scope.categoryList = result;
            }, alertService.error);


        function addcategory(category) {
            $scope.categoryList.splice(0, 0, category);
        }

        $scope.enable = function (category) {
            trainningService.enableAsync(category.Id, category.Enabled, 'TrainningCategory')
                .then(function () {
                    category.Enabled = !category.Enabled;
                }, alertService.error);
        }

        $scope.createOrUpdate = function (category) {
            var modelInstance = $modal.open({
                templateUrl: 'tpl/app-trainning-category-edit.html',
                windowClass: 'response-modal',
                backdrop: false,
                controller: [
                    '$scope', 'trainningService', 'accountService',
                    function ($scope, trainningService, accountService) {
                        $scope.category = { Id: 0 };
                        var curUser = accountService.getLocalUserData();

                        if (angular.isDefined(category)) {
                            $scope.category = angular.extend({}, category);
                        }

                        $scope.submit = function () {
                            trainningService.createOrUpdateAsync($scope.category, 'TrainningCategory')
                                .then(function (result) {
                                    if ($scope.category.Id > 0) {
                                        //更新
                                        $scope.category.UpdateId = curUser.UserId;
                                        $scope.category.UpdateUser = curUser.RealName;
                                        $scope.category.UpdateTime = new Date();
                                        angular.extend(category, $scope.category);
                                    } else {//新增
                                        $scope.category.Id = result;
                                        $scope.category.CreateId = curUser.UserId;
                                        $scope.category.CreateUser = curUser.RealName;
                                        $scope.category.CreateTime = new Date();
                                        addcategory($scope.category);
                                    }
                                    modelInstance.dismiss('ok');
                                }, alertService.error);
                        };

                        $scope.miss = function () {
                            modelInstance.dismiss();
                        };
                    }
                ]
            });
        };
    }
]);


app.controller('TrainningCtrl', [
    '$scope', 'alertService', 'trainningService', '$modal',
    function ($scope, alertService, trainningService, $modal) {
        $scope.form = {};
        trainningService.getAsync(true, 'TrainningCategory')
            .then(function (result) {
                $scope.categoryList = result;
                $scope.form.categoryId = result[0].Id;
                loadTrainnings();
            }, alertService.error);

        function loadTrainnings() {
            trainningService.getAsync(false, 'Trainning', $scope.form.categoryId)
                .then(function (result) {
                    $scope.trainningList = result;
                }, alertService.error);
        }

        function addTrainning(trainning) {
            $scope.trainningList.splice(0, 0, trainning);
        }
        
        $scope.search=loadTrainnings;
        
        $scope.enable = function (trainning) {
            trainningService.enableAsync(trainning.Id, trainning.Enabled, 'Trainning')
                .then(function () {
                    trainning.Enabled = !trainning.Enabled;
                }, alertService.error);
        }

        $scope.createOrUpdate = function (trainning) {
            var categoryList = $scope.categoryList;
            var modelInstance = $modal.open({
                templateUrl: 'tpl/app-trainning-edit.html',
                windowClass: 'response-modal',
                backdrop: false,
                controller: [
                    '$scope', 'trainningService', 'accountService',
                    function ($scope, trainningService, accountService) {
                        $scope.trainning = { Id: 0 };
                        $scope.categoryList = categoryList;
                        var curUser = accountService.getLocalUserData();

                        if (angular.isDefined(trainning)) {
                            $scope.trainning = angular.extend({}, trainning);
                        }
                        
                        function first(obj,key,value){
                            for(var i=0;i<obj.length;i++){
                                if(obj[i][key]==value){
                                    return obj[i];
                                }
                            }
                        }

                        $scope.submit = function () {
                            trainningService.createOrUpdateAsync($scope.trainning, 'Trainning')
                                .then(function (result) {
                                    if ($scope.trainning.Id > 0) {
                                        //更新
                                        $scope.trainning.UpdateId = curUser.UserId;
                                        $scope.trainning.UpdateUser = curUser.RealName;
                                        $scope.trainning.UpdateTime = new Date();
                                        $scope.trainning.Category=first(categoryList,'Id',$scope.trainning.CategoryId).Name;
                                        angular.extend(trainning, $scope.trainning);
                                    } else {//新增
                                        $scope.trainning.Id = result;
                                        $scope.trainning.CreateId = curUser.UserId;
                                        $scope.trainning.CreateUser = curUser.RealName;  
                                        $scope.trainning.Category=first(categoryList,'Id',$scope.trainning.CategoryId).Name;
                                        $scope.trainning.CreateTime = new Date();
                                        addTrainning($scope.trainning);
                                    }
                                    modelInstance.dismiss('ok');
                                }, alertService.error);
                        };

                        $scope.miss = function () {
                            modelInstance.dismiss();
                        };
                    }
                ]
            });
        };
    }
]);


app.controller('TrainningEnrollCtrl', [
    '$scope', 'alertService', 'trainningService','$modal',
    function ($scope, alertService, trainningService,$modal) {
        $scope.searchForm = {
            Start: new Date(),
            End:new Date()
        };
        $scope.page = {
            index: 1,
            size: 10,
            total: 0
        };
        trainningService.getCategoryiesWithTrainningsAsync()
            .then(function (result) {
                result.splice(0, 0, {
                    Id: 0,
                    Name: '全部',
                    Trainnings: [{
                        Id: 0,
                        Title: '全部'
                    }]
                });
                $scope.categoryList = result;
                $scope.searchForm.Category = $scope.categoryList[0];
                $scope.searchForm.TrainningId = $scope.searchForm.Category.Trainnings[0].Id;
            }, alertService.error);

        $scope.openCalendar = function ($event, target) {
            $event.preventDefault();
            $event.stopPropagation();
            if (target === 'start') {
                $scope.isStartOpen = true;
            }
            else if (target === 'end') {
                $scope.isEndOpen = true;
            }
        };

        function loadEnrolls(index) {
            if ($scope.searchForm.Start > $scope.searchForm.End) {
                alertService.add('开始日期不能大于结束日期');
                return;
            }
            trainningService.searchAsync($scope.searchForm.TrainningId || 0,$scope.searchForm.Phone||'', $scope.searchForm.Start,
                $scope.searchForm.End, index || $scope.page.index, $scope.page.size)
                .then(function (result) {
                    $scope.enrollList = result.data;
                    $scope.page.total = result.total;
                    if (result.total == 0 && index == 1) {
                        alertService.add("没有查询到数据");
                    }
                }, alertService.error);
        }

        $scope.$watch('page.index', function (newVal, oldVal) {
            if (!newVal || newVal === oldVal) return;
            loadEnrolls();
        });

        $scope.$watch('page.size', function (newVal, oldVal) {
            if (!newVal || newVal === oldVal) return;
            loadEnrolls();
        });

        $scope.search = function() {
            loadEnrolls(1);
        };

        $scope.audit = function(enroll) {
            var modelInstance = $modal.open({
                templateUrl: 'tpl/app-trainning-enroll-audit.html',
                windowClass: 'response-modal',
                backdrop: false,
                controller: [
                    '$scope', 'trainningService',
                    function (scope, trainningService) {
                        scope.auditForm = { description: '', status: 1 };
                        scope.submit = function () {
                            if (scope.auditForm.status == 2 && scope.auditForm.description == '') {
                                alertService.add('请输入不通过的原因');
                                return;
                            }
                            trainningService.auditAsync(enroll.Id, scope.auditForm.status, scope.auditForm.description)
                                .then(function (result) {
                                    enroll.EnrollStatus = scope.auditForm.status;
                                    modelInstance.dismiss('ok');
                                }, alertService.error);
                        };

                        scope.miss = function () {
                            modelInstance.dismiss();
                        };
                    }
                ]
            });
        };
    }
]);


app.factory('trainningService', [
    '$http', '$q',
    function ($http, $q) {
        var self = {};

        self.getAsync = function (onlyEnabled, controller, categoryId) {
            var defer = $q.defer();
            var httpConfig = {
                url: '/api/' + controller,
                params: { onlyEnabled: onlyEnabled }
            };
            if (angular.isDefined(categoryId)) httpConfig.params.categoryId = categoryId;

            $http(httpConfig).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('查询列表失败，请稍后再试');
            });

            return defer.promise;
        };

        self.enableAsync = function (id, enabled, controller) {
            var defer = $q.defer();
            $http({
                url: '/api/' + controller + '/' + (enabled ? 'Delete' : 'Resume'),
                method: 'POST',
                params: { id: id }
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('操作失败，请稍后再试');
            });

            return defer.promise;
        };

        self.createOrUpdateAsync = function (model, controller) {
            var defer = $q.defer();
            $http({
                url: '/api/' + controller + '/' + (model.Id > 0 ? 'Update' : 'Create'),
                method: 'POST',
                data: model
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Code);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('提交失败，请稍后再试');
            });

            return defer.promise;
        };

        self.getCategoryiesWithTrainningsAsync = function() {
            var defer = $q.defer();
            $http({
                url: '/api/TrainningCategory/GetCategoryiesWithTrainnings'
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(result.Data);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('查询培训列表失败，请稍后再试');
            });

            return defer.promise;
        };

        self.searchAsync = function(trainningId, phone, start, end, pageIndex, pageSize) {
            var defer = $q.defer();
            $http({
                url: '/api/Trainning/Search',
                params: {
                    trainningId: trainningId,
                    phone: phone,
                    start: moment(start).format('YYYY-MM-DD'),
                    end: moment(end).format('YYYY-MM-DD'),
                    pageIndex: pageIndex,
                    pageSize:pageSize
                }
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve({ total: result.Code, data: result.Data });
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('查询报名数据失败，请稍后再试');
            });

            return defer.promise;
        };

        self.auditAsync = function(enrollId, status, description) {
            var defer = $q.defer();
            $http({
                method:'POST',
                url: '/api/Trainning/Audit',
                params: {
                    enrollId: enrollId,
                    statusId: status,
                    description: description
                }
            }).success(function (result) {
                if (result.Code >= 0) defer.resolve(true);
                else defer.reject(result.Message);
            }).error(function (x) {
                defer.reject('提交审核失败，请稍后再试');
            });
            return defer.promise;
        };

        return self;
    }
]);